package work.zhengyun.demo.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import work.zhengyun.demo.dao.RoleDao;
import work.zhengyun.demo.dao.UserRoleDao;
import work.zhengyun.demo.entity.Role;
import work.zhengyun.demo.entity.User;
import work.zhengyun.demo.entity.UserRole;
import work.zhengyun.demo.service.RoleService;
import work.zhengyun.demo.service.UserService;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author zhengyun
 * @date 2019/11/27 16:14
 */
@Service
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleDao roleDao;
    @Autowired
    private UserRoleDao userRoleDao;

    /**
     * 通过 用户名 获取 他拥有的所有角色名
     */
    @Override
    public Set<String> listRoleName(User user) {
        List<Role> roles = listRoleByUser(user);
        Set<String> result = new HashSet<>();
        for (Role role : roles) {
            result.add(role.getName());
        }
        return result;
    }
    /**
     * 通过 用户 获取 他拥有的所有角色
     */
    @Override
    public List<Role> listRoleByUser(User user) {
        List<Role> roles = new ArrayList<>();

        List<UserRole> userRoles = userRoleDao.findUserRolesByUserId(user.getId());

        for (UserRole userRole : userRoles) {
            Role role = roleDao.findByPrimaryKey(userRole.getRoleId());
            roles.add(role);
        }
        return roles;
    }

}
